/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, ScrollView, StyleSheet, View} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from "../../../res/language/i18n";
import IparInput from "../../../custom/IparInput";
import CommonUtils from "../../../common/CommonUtils";
import AlertDialog from "../../../custom/AlertDialog";

export default class SendMoneyPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false,
        };
        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
    }

    componentDidMount() {

        CommonUtils.getAcyncInfo('userInfo')
            .then((res) => {
                this.userData = JSON.parse(res);
            });

    }


    /**
     * 获取用户信息
     */
    getUserInfo() {
        if (!this.sendToText) {
            return;
        }

        CommonUtils.showLoading();
        this.iparNetwork.getRequest(SERVER_TYPE.uiAdminIpar + 'getUserTransferInfo?', 'keywords=' + this.sendToText)
            .then((result) => {
                if (result.code === 200) {//用户已存在
                    let data = result.data;
                    if (this.userData.main_user_id === data.main_user_id) {
                        CommonUtils.dismissLoading();
                        DeviceEventEmitter.emit('toast', I18n.t('toast.loginUserNotExist'));
                        return;
                    }

                    if (this.userData.country !== data.country) {
                        CommonUtils.dismissLoading();
                        DeviceEventEmitter.emit('toast', I18n.t('toast.loginUserNotExist'));
                        return;
                    }

                    console.log(result);
                    this.accountProfile(data);
                } else {//用户未存在
                    CommonUtils.dismissLoading();
                    DeviceEventEmitter.emit('toast', I18n.t('toast.loginUserNotExist'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))


            });
    }


    /**
     * synpays获取用户信息
     */
    accountProfile(userData) {
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'Profile?', 'UserID=' + userData.main_user_id)
            .then((result) => {
                CommonUtils.dismissLoading();
                console.log(result);
                if (result.code === 200) {
                    this.sendToUserInfo = result.data;
                    this.setState({
                        alertVisible: true,
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('toast.loginUserNotExist'))
                }
            })
            .catch((error) => {
                console.log('SendMoneyPage---accountProfile-' + error);
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('toast.loginUserNotExist'))
            });
    }


    onPressBtn() {
        if (!this.amountText) {
            DeviceEventEmitter.emit('toast', 'amount');
            return;
        }

        if (!this.sendToText) {
            DeviceEventEmitter.emit('toast', 'sendTo');
            return;
        }

        if (!this.sendToUserInfo) {
            DeviceEventEmitter.emit('toast', I18n.t('pay.receiver'));
            return;
        }

        if (!this.userPass) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterYourPassword'));
            return;
        }

        this.verificationPassword()
    }


    /**
     * 验证用户登录密码
     */
    verificationPassword() {
        CommonUtils.showLoading();
        let formData = new FormData();
        formData.append('name', this.userData.mobile);
        formData.append('password', this.userPass);
        this.iparNetwork.getPostFrom(SERVER_TYPE.centerIpar + 'login', formData)
            .then((result) => {
                if (result.code === 200) {
                    this.submit();
                } else {
                    this.setState({showLoading: false,});
                    CommonUtils.dismissLoading();
                    if (result.message === '密码错误') {
                        DeviceEventEmitter.emit('toast', I18n.t('toast.passwordNo'))
                    } else {
                        DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                    }
                }

            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                console.log('loginPage erroe--' + error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })
    }


    submit() {
        let data = {
            UserID: this.userData.main_user_id,
            SendTo: this.sendToUserInfo.main_user_id,
            Amount: this.amountText,
            Note: this.note || ' ',
            Country: this.userData.country,
        };

        let formData = new FormData();

        formData.append("UserID", this.userData.main_user_id);
        formData.append("SendTo", this.sendToUserInfo.user_id);
        formData.append("Amount", this.amountText);
        formData.append("Note", this.note || ' ');
        formData.append("Country", this.userData.country);

        console.log(data);
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'Transfer', formData)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.pop();
                    this.props.callBack();
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
                console.log(result)
            })
            .catch((err) => {
                CommonUtils.dismissLoading();
                console.log(err);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })
    }


    render() {

        const {alertVisible} = this.state;
        const {balance} = this.props;

        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                />
                <ScrollView>
                    <View style={[StyleUtils.flex, {padding: 16}]}>
                        {ViewUtils.getTitleView(I18n.t('pay.transfer'), balance)}

                        <IparInput
                            onChangeText={(text) => this.amountText = text}
                            keyboardType={'numeric'}
                            placeholder={I18n.t('pay.amount')}/>

                        <IparInput
                            onChangeText={(text) => this.sendToText = text}
                            onBlur={() => this.getUserInfo()}
                            placeholder={I18n.t('pay.receiver')}/>


                        <IparInput
                            onChangeText={(text) => this.note = text}
                            placeholder={'Note'}/>

                        <IparInput
                            isPassword={true}
                            onChangeText={(text) => this.userPass = text}
                            placeholder={I18n.t('default.enterYourPassword')}/>

                        {ViewUtils.getButton(I18n.t('default.submit'), () => this.onPressBtn(), {marginTop: 30})}
                    </View>

                </ScrollView>


                <AlertDialog
                    visible={alertVisible}
                    requestClose={() => {
                        this.setState({
                            alertVisible: true,
                        })
                    }}
                    leftSts={'ok'}
                    contentTv={this.sendToUserInfo ? I18n.t('default.confirmUserInformation') + '\n\n\n' +
                        I18n.t('default._phoneNumber') + ': ' + this.sendToUserInfo.mobile +
                        '\n\nIpar ID: ' + this.sendToUserInfo.rand_id : ''}
                    leftBtnOnclick={() => {
                        this.setState({
                            alertVisible: false,
                        })
                    }}
                    rightBtnOnclick={() => {
                        this.sendToUserInfo = null;
                        this.setState({
                            alertVisible: false,
                        })
                    }}
                />

            </View>)
    }


}

